<template>
    <div class="add-activity">
        <el-dialog title="添加活动" :visible.sync="visible.isShow" size="tiny">
            <el-form :model="formInline"  :rules="rules" label-width="115px" ref="formInline">
            <div class="form-item">
                <div class="form-item-title">
                    <span class="title-level">活动名称</span>
                </div>
             </div>
            <el-row :gutter="41">
                <el-col>
                    <el-form-item label="活动名称" prop="activeName">
                        <el-input v-model.trim="formInline.activeName" class="input-item"  :maxlength="12"  placeholder="请输入活动名称" style="width:85%"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
             <div class="form-item-title">
                <span class="title-level">活动设置</span>
            </div>
            <el-row :gutter="41">
                <el-col>
                    <el-form-item label="活动日期范围" prop="daterange" required>
                        <el-date-picker  class="input-item" style="width:85%" v-model="formInline.daterange"
                        type="daterange"
                        :editable="false"
                        :picker-options="formInline.pickerOptions"
                        placeholder="开始日期~结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col> 
            </el-row>
            <el-row :gutter="41">
                <el-col>
                <el-form-item label="学生提交人数" prop="submitNumber" class="input-wrapper">
                    <el-input  v-model.trim="formInline.submitNumber"  class="input-item"   placeholder="请输入提交人数" style="width:85%" type="number"></el-input>
                    <span>人</span>
                </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="41">
                <el-col >
                <el-form-item label="话费赠送金额" prop="telFare">
                   <el-input  v-model.trim="formInline.telFare" class="input-item"  placeholder="请输入赠送金额" style="width:85%" type="number"></el-input>
                    <span>元</span>
                </el-form-item>
                </el-col>
            </el-row>
        </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('formInline')">取 消</el-button>
                <el-button type="primary" @click="updateForm('formInline')" :loading="loadingBtn">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment';
import { postAddTask, getTimeRange} from 'api/newTask.js';

export default {
    props: {
        visible: {
            default() {
                return {
                    isShow: false
                }
            }
        }
    },
    data() {
        // 日期范围验证
        var checkAge = (rule, value, callback) => {
            if (!(value[0]&&value[1])) {
                callback(new Error('请选择活动日期范围'));
            } else {
                let startCheckTime = moment(value[0]).format('YYYY-MM-DD HH:mm:ss');
                let endCheckTime =moment(value[1]).format('YYYY-MM-DD')+' 23:59:59';
                this.proveTimeRange(startCheckTime, endCheckTime).then(response => {
                    if (response) {
                        callback(new Error('请选择正确的活动日期范围'));
                    } else {
                        callback();
                    }
                }) 
               
            }
        };

        // let numSet = (rule, value, callback) => {
        //     let reg = /^\d*$/;
        //     if (!reg.test(value)) {
        //         console.log(value, '===========')
        //         this.formInline.submitNumber = 123;
        //     } else {
        //         callback();
        //     }
        // };

        // 话费赠送金额验证
        // var checkMoney = (rule, value, callback) => {
        //     if (!value) {
        //         callback(new Error('请填写话费赠送金额'));
        //     } else {
        //         if (value < 1 || value > 99) {
        //             callback(new Error('可输入范围为1-99'));
        //         } else {
        //             let reg = /(^[1-9]([0-9]+)?(\.[0-9]{1})?$)|(^(0){1}$)|(^[0-9]\.[0-9]?$)/;
        //             if (!reg.test(value)) {
        //                 callback(new Error('金额必须为1~99的金额值'));
        //             } else {
        //                 callback();
        //             }
        //         }
        //     }
        // };
        return {
            loadingBtn: false,
            formInline: {
                activeName: '',
                daterange: [],
                submitNumber: '',
                telFare: '',
                startDate: '',
                endDate: '',
                pickerOptions: {}
            },
            
            rules: {
                activeName: [
                        { required: true, message: '请填写活动名称', trigger: 'blur'}
                ],
                daterange: [
                        { validator: checkAge, trigger: 'blur , change' }
                ],
                submitNumber: [
                        { required: true, message: '请填写学生提交人数', trigger: 'blur'},
                        { pattern: /^\+?[1-9][0-9]*$/, message: '人数必须为1~99的正整数', trigger: 'blur'},
                        { pattern: /^[1-9][0-9]?$/, message: '可输入范围为1-99', trigger: 'blur'}
                        // { validator: numSet, trigger: 'change'}
                ],
                telFare: [
                        { required: true, message: '请填写话费赠送金额', trigger: 'blur'},
                        { pattern: /^\+?[1-9][0-9]*$/, message: '金额必须为1~99的正整数', trigger: 'blur,change'},
                        { pattern: /^[1-9][0-9]?$/, message: '可输入范围为1-99', trigger: 'blur'}
                ]
            }
        }
    },
    // watch: {
    //     // 允许数据输入 
    //     'formInline.submitNumber': {
    //         handler(val, oldVal) {
    //             let reg = /^\d*$/;
    //             if (!reg.test(val)) {
    //                 console.log(344444);
    //                 return ''
    //             }
    //         },
    //         deep: true,
    //         immediate: true
    //     }
        
    // },
    created() {  
        this.disabledDate();
    },
    methods: {
        // 取消
        resetForm(formInline) {
            this.cancelDialog();
        },
       
        // 确认
        updateForm(form) {
            this.$refs[form].validate((rule) => {
                if (rule) { // 表单验证成功        
                    let startDate = this.formInline.daterange[0]?moment(this.formInline.daterange[0]).format('YYYY-MM-DD HH:mm:ss'):'';
                    let endDate = this.formInline.daterange[1]?moment(this.formInline.daterange[1]).format('YYYY-MM-DD')+' 23:59:59':'';
                    // 调用接口
                    if (this.formInline.activeName && this.formInline.submitNumber && this.formInline.telFare && startDate && endDate) {
                        this.loadingBtn = true;
                        postAddTask(this.formInline.activeName, this.formInline.submitNumber, this.formInline.telFare, startDate, endDate).then(data => {
                            this.loadingBtn = false;
                            this.$message({
                                type: 'success',
                                message: data.data.errorMsg
                            })
                            this.$emit('update-list');
                            this.cancelDialog();
                        })        
                    }
                } else {
                    return false;
                }
            })
        },
        
        // // 允许数据输入 
        // changeNumber() {
        //     console.log(22222)
        //     // let reg = /^\d*$/;
        //     // if (!reg.test(this.formInline.submitNumber)) {
        //     //     console.log(344444);
        //     //     console.log(this.formInline.submitNumber);
        //     //     this.formInline.submitNumber = '';
        //     // }
        // },
        // 关闭弹窗
        cancelDialog() {
            this.visible.isShow = false;
        },

        // 返回不可选的时间数组
        getTime() {
            return new Promise((resolve, reject) => {
                getTimeRange().then(data => {
                    let temp = data.data.content;
                    let list = temp.map(item => {
                        return {
                            startTime: item.startDate,
                            endTime: item.endDate
                        }
                    })
                    resolve(list);
                })   
            })
        },
        // 时间段选择验证
        proveTimeRange(startCheckTime, endCheckTime) {
            let state=false;
            return new Promise((resolve, reject) => {
                this.getTime().then(data => {
                    if (data.length) {
                        data.forEach(val => {
                            if (startCheckTime<val.startTime&&endCheckTime>val.endTime) {
                                state=true;
                            }
                        })
                    }
                    resolve(state);
                });

            })
            
        },
        // 不可选的时间
        disabledDate(time) {
            this.getTime().then(data => {
                this.formInline.pickerOptions = {
                    disabledDate(time) {
                        if (data.length) {
                            return data.some(function(item) {
                                if (Date.now() >= Date.parse(item.startTime) && (Date.now() <= Date.parse(item.endTime))) {
                                    return time.getTime() < Date.now() || (time.getTime() >= Date.parse(item.startTime) && time.getTime() <= Date.parse(item.endTime));    
                                }
                                return time.getTime() < Date.now() - 864e5 || (time.getTime() >= Date.parse(item.startTime) && time.getTime() <= Date.parse(item.endTime));
                            });
                        } else {
                            return time.getTime() < Date.now() - 864e5;
                        }
                    }
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.add-activity{
    .form-item-title {
        margin: 40px 0;
        font-size: 14px;
        color: #333;
        line-height: 14px;
        border-left: 4px solid #ff5e2c;
        text-indent: 16px;
    }
    .input-item {
        margin-right:15px;
    }
   
}

</style>
